<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<style>
    #progress { position:relative; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
    #bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
    #percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(function(){

        var AddPhotoController = Backbone.Router.extend({
            routes: {
                "addPhotoClose": "close",
                "addPhoto/:id": "addPhoto",
                "deletePhoto/:id": "deletePhoto"
            },

            close: function () {
                addPhotoView.closeDialog();
                this.navigate("", {trigger: false, replace: true});
            },
            addPhoto: function(id) {
                addPhotoModel.setRealty(id);
                addPhotoView.openDialog();
                this.navigate("", {trigger: false, replace: true});
            },
            deletePhoto: function(id) {
                addPhotoModel.deletePhoto(id);
                this.navigate("", {trigger: false, replace: true});
            }
        });


        AddPhotoModel = Backbone.Model.extend({
            defaults: {
                realtyId: 1,
                description: "",
                photos: [],
                mainPhotoId: 0
            },
            setRealty: function(realtyId) {
                this.set(this.defaults, {silent: true});
                this.set("realtyId", realtyId);
                this.trigger("render");
                this.loadPhotos();
            },
            loadPhotos: function() {
                var self = this;
                $.ajax({
                    type: "GET",
                    url: "/photo/getPhotos.do",
                    dataType: "JSON",
                    data:{realtyId: self.get("realtyId")},
                    success: function(response) {
                        self.set("photos", response);
                        var mainPhotoId = null;
                        for (var i in response) {
                            if (response[i].mainPhoto) {
                                mainPhotoId = response[i].id;
                                break;
                            }
                        }
                        self.set("mainPhotoId", mainPhotoId);
                        self.trigger("renderPhotos");
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        self.set("photos", []);
                        self.set("mainPhotoId", 0);
                        self.trigger("renderPhotos");
                        alert("Ошибка при загрузке данных. Проверьте соединение");
                    }
                });
            },
            deletePhoto: function(id) {
                var self = this;
                $.dialog("dialogDeletePhoto", {
                    title: "Удалении фото",
                    body: "Вы действительно хотите удалить фото?",
                    active_button: "Ok",
                    buttons: {
                        "Ok": function() {
                            $.ajax({
                                type: "GET",
                                url: "/photo/deletePhoto.do",
                                dataType: "JSON",
                                data:{photoId: id},
                                success: function(response) {
                                    console.log("Response delete:");
                                    console.log(response);
                                    if (!response.error) {
                                        self.loadPhotos();
                                    } else {
                                        alert("Ошибка удаления фото: " + response.message);
                                    }
                                }
                            });
                            $.dialog("dialogDeletePhoto", "close");
                        },
                        "Отмена": function() {
                            $.dialog("dialogDeletePhoto", "close");
                        }
                    }
                });

            },
            changeMainPhoto: function(photoId, callBackSuccess, callBackError) {
                var self = this;
                $.ajax({
                    type: "GET",
                    url: "/photo/setMainPhoto.do",
                    dataType: "JSON",
                    data:{
                        realtyId: self.get("realtyId"),
                        photoId: photoId
                    },
                    success: function(response) {
                        if (!response.error) {
                            self.set("mainPhotoId", photoId);
                            if (callBackSuccess) {
                                callBackSuccess(response);
                            }
                        } else {
                            if (callBackError) {
                                callBackError(response);
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        callBackError(null, textStatus);
                    }
                });
            }
        });


        AddPhotoView = Backbone.View.extend({
            initialize: function(){
                this.model.bind("render", this.render, this);
                this.model.bind("renderPhotos", this.renderPhotos, this);
                var self = this;
                var options = {
                    beforeSubmit: function() {
                        if (!self.$el.find("input[name=file]").val()) {
                            $.dialog("dialogAlertPhotoUploadEmptyFile", {
                                title: "Ошибка загрузки фотографии",
                                body: "Выберите файл для загрузки",
                                active_button: "Ok",
                                buttons: {
                                    "Ok": function() {
                                        $.dialog("dialogAlertPhotoUploadEmptyFile", "close");
                                    }
                                }
                            });
                            return false;
                        }
                        return true;
                    },
                    beforeSend: function() {
                        $("#progress").show();
                        $("#bar").show();
                        $("#percent").show();
                        $("#bar").width('0%');
                        $("#percent").html("0%");
                    },
                    uploadProgress: function(event, position, total, percentComplete) {
                        $("#bar").width(percentComplete+'%');
                        $("#percent").html(percentComplete+'%');
                    },
                    success: function() {
                        $("#bar").width('100%');
                        $("#percent").html('100%');
                        addPhotoModel.loadPhotos();
                    },
                    complete: function(response) {
                        $("#progress").hide();
                        $("#bar").hide();
                        $("#percent").hide();
                        var response = JSON.parse(response.responseText);
                        if (response.error) {
                            $.dialog("dialogAlertPhotoUpload", {
                                title: "Ошибка загрузки фотографии",
                                body: "Ошибка при загрузке фотографии. " + response.message,
                                active_button: "Ok",
                                buttons: {
                                    "Ok": function() {
                                        $.dialog("dialogAlertPhotoUpload", "close");
                                    }
                                }
                            });
                        } else {
                            self.clearFile();
                        }

                    },
                    error: function() {
                        $("#progress").hide();
                        $("#bar").hide();
                        $("#percent").hide();
                        $.dialog("dialogAlertPhotoUpload2", {
                            title: "Ошибка загрузки фотографии",
                            body: "Ошибка при загрузке фотографии. Проблема с передачью данных.",
                            active_button: "Ok",
                            buttons: {
                                "Ok": function() {
                                    $.dialog("dialogAlertPhotoUpload2", "close");
                                }
                            }
                        });
                    }

                };

                $("#uploadPhotoForm").ajaxForm(options);

                $(".photoOnFancyBox").fancybox({
                    helpers : {
                        title: {
                            type: 'inside'
                        }
                    },
                    nextEffect: 'fade',
                    prevEffect: 'fade',
                    'overlayShow'	:	true,
                    'imageScale'    :   true,
                    'closeBtn'      :   true
                });

                $("#parentContainerMainPhoto").droppable({
                    tolerance : 'intersect',
                    accept : ' div.containerPhoto',
                    drop : function(event, ui) {
                        self.model.changeMainPhoto($(ui.draggable).data('photo-id'),
                            function (response) {
                                $("#containerMainPhoto").empty();
                                $("#containerMainPhoto").append($(ui.draggable).clone());
                            },
                            function (response, textStatus) {
                                self.model.loadPhotos();
                                alert("Ошибка при изменении главного фото:" + (response ? response.message : "status - " + textStatus));
                            }
                        );
                    }
                });
            },
            render: function(){
                this.$el.find("[name=realtyId]").val(this.model.get('realtyId'));
                this.$el.find("[name=description]").val(this.model.get('description'));
                this.$el.find("#progress").hide();
                this.$el.find("#bar").hide();
                this.$el.find("#percent").hide();
                this.$el.find("#containerMainPhoto").html("<h3>Перетащите сюда фотографию</h3>");
            },
            renderPhotos: function() {
                this.$el.find("#containerMainPhoto").html("<h3>Перетащите сюда фотографию</h3>");
                this.$el.find("#realtyPhotosDiv").empty();
                var photos = this.model.get("photos");
                for (var i in photos) {
                    var newPhotoContainer =
                            '<div style="padding: 5px;float: left;" class="containerPhoto" data-photo-id="' + photos[i].id + '">' +
                                    '   <a class="photoOnFancyBox" rel="photoSet" href="/resources/photo/' + photos[i].fileName + '" title="' + photos[i].description + '">' +
                                    '       <img width="60px" height="60px" src="/resources/photo/' + photos[i].fileName + '"/>' +
                                    '   </a>' +
                                    '   <div style="text-align: center;">' + photos[i].description + '<br><a href="#deletePhoto/'+ photos[i].id + '">Удалить</a></div>' +
                            '</div>';
                    this.$el.find("#realtyPhotosDiv").append(newPhotoContainer);
                    if (photos[i].id == this.model.get("mainPhotoId")) {
                        this.$el.find("#containerMainPhoto").html(newPhotoContainer);
                    }
                }
                this.$el.find('#realtyPhotosDiv div.containerPhoto').draggable({
                    helper : 'clone',
                    opacity : 0.6
                });

            },
            clearFile: function() {
                this.$el.find("[name=file]").val("");
            },
            events: {
            },
            openDialog : function () {
                this.$el.modal('show');
            },
            closeDialog : function() {
                this.$el.modal("hide");
            }
        });

        addPhotoController = new AddPhotoController();
        addPhotoModel = new AddPhotoModel();
        addPhotoView = new AddPhotoView({ el: "#formAddPhoto", model: addPhotoModel, controller: addPhotoController });

    });
</script>

<div id="formAddPhoto" class="modal hide fade" style="width:716px;">
    <div class="modal-header">
        <a class="close" href="#addPhotoClose">&times;</a>
        <h3>Загрузка фотографий</h3>
    </div>

    <div class="modal-body">
        <div class="row">
            <div id="realtyPhotosDiv" class="span9">
            </div>
            <div class="span5" style="border: 1px solid #ddd;padding:10px;">
                <form id="uploadPhotoForm" action="/photo/postPhoto.do" method="post" enctype="multipart/form-data">
                    <label>Приложите файл фотографии(png, jpg, jpeg, bmp):<br/>
                        <input type="file" class="span4" size="6000000000" name="file" placeholder="Выберите файл">
                    </label>
                    <label>Описание:
                        <input type="text" name="description"/>
                    </label>
                    <div style="float:left;">
                        <button type="submit" style="float:left;" class="btn btn-primary">Приложить</button>
                    </div>

                    <div id="progress" style="margin-left:100px;">
                        <div id="bar"></div>
                        <div id="percent">0%</div >
                    </div>

                    <input type="hidden" name="realtyId"/>
                </form>
            </div>
            <div id="parentContainerMainPhoto" class="span3" style="border: 1px solid #ddd;padding:10px;text-align: center;">
                <div style="text-align: center;">Фасадное фото</div>
                <div id="containerMainPhoto" class="" style="width:100px; height:100px;text-align: center;"></div>
            </div>
        </div>

    </div>
    <div class="modal-footer">
        <a href="#addPhotoClose" class="btn btn-primary" name="complete">Готово</a>
    </div>
</div>